package cn.itrip.auth.service;

import java.util.HashMap;
import java.util.Set;

import cn.itrip.utlis.RandomUtils;
import cn.itrip.utlis.RedisAPI;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;


public class SmsService {
    private String serverIP;
    private String  serverPort;
    private String  sid;
    private String  token;
    private String appId;
    private String templateId;

    private RedisAPI redisAPI;

    public void setRedisAPI(RedisAPI redisAPI) {
        this.redisAPI = redisAPI;
    }

    public void setServerIP(String serverIP) {
        this.serverIP = serverIP;
    }

    public void setServerPort(String serverPort) {
        this.serverPort = serverPort;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }


    public  String send(String phoneNumber) {

        Long ex = redisAPI.ttl(phoneNumber);
        if(ex>60 * 4){
            return "1";
        }
        String code = RandomUtils.random(4);
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = "8aaf0708762cb1cf01764f3ac9f80c57";
        String accountToken = "d57e409760b242b49c3c4186e1dabe54";
        //请使用管理控制台中已创建应用的APPID
        String appId = "8aaf0708762cb1cf01764f3acafb0c5d";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String templateId= "1";
        String[] datas = {code,"5"};
//        String subAppend="1234";  //可选 扩展码，四位数字 0~9999
//        String reqId="fadfafas";  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        HashMap<String, Object> result = sdk.sendTemplateSMS(phoneNumber,templateId,datas);
//        HashMap<String, Object> result = sdk.sendTemplateSMS(phoneNumber,templateId,datas,subAppend,reqId);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
            //保存到redis
            String key =  phoneNumber;
            redisAPI.setex(key,5*60,code);
            return code;
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            return "error";
        }

    }

}
